package com.gongpingjialoan.api;

import com.gongpingjialoan.global.GPJApplication;
import com.umeng.socialize.net.utils.Base64;

import java.net.URL;
import java.net.URLConnection;
import java.sql.Date;
import java.text.SimpleDateFormat;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

/**
 * Created by Administrator on 2017/10/17.
 */

public class ApiSecurity {

    public static String security(String secret,String phone){
//        secret = "KzKwdx5Mv8Gzx^%OoLZS*lWbkEPmQ$mg";
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
//        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        long ld = System.currentTimeMillis();
        try {
            URL url = new URL("http://www.bjtime.cn");
            URLConnection uc=url.openConnection();//生成连接对象
            uc.connect(); //发出连接
            ld=uc.getDate(); //取得网站日期时间
        } catch (Exception e) {
            e.printStackTrace();
        }
        Date curDate = new Date(ld);//获取当前时间
//        JSONObject jo = new JSONObject();
//        try {
//            jo.put("phone",phone);
//            jo.put("device_code", GPJApplication.getInstance().getDeviceCode());
//            jo.put("date",formatter.format(curDate));
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
//        String messtr = jo.toString();
//        String message = messtr.replace("\"","\'").trim();
        String message = String.format("phone=%s&device_code=%s&date=%s", phone, GPJApplication.getInstance().getDeviceCode(),formatter.format(curDate));
        try {
            Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
            SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
            sha256_HMAC.init(secret_key);

            String hash = Base64.encodeBase64String(sha256_HMAC.doFinal(message.getBytes()));
//            System.out.println("===========>>>");
//            System.out.println(hash);
            return hash;
        }
        catch (Exception e){
            System.out.println("Error");
        }
        return null;
    }
}
